package xxh;

import javax.swing.table.DefaultTableModel;
import java.sql.*;

public class BorrowRecordProcess {
    private Connection connection;

    BorrowRecordProcess() throws SQLException {
        connection = ConnectDB.getConnection();
    }

    public void loadBorrowRecords(DefaultTableModel tableModel, String userNo) throws SQLException {
        // 清空表格数据
        tableModel.setRowCount(0);

        // 查询语句
        String sql = """
                SELECT 
                    lend.Uno, 
                    user.Uname, 
                    lend.Bno, 
                    books.Bname, 
                    lend.Lendtime, 
                    lend.Backtime 
                FROM lend
                JOIN user ON lend.Uno = user.Uno
                JOIN books ON lend.Bno = books.Bno
                """;
        if (userNo != null) {
            sql += " WHERE lend.Uno = ?";
        }

        try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            if (userNo != null) {
                preparedStatement.setString(1, userNo);
            }

            try (ResultSet rs = preparedStatement.executeQuery()) {
                while (rs.next()) {
                    String uno = rs.getString("Uno");
                    String uname = rs.getString("Uname");
                    String bno = rs.getString("Bno");
                    String bname = rs.getString("Bname");
                    Date lendTime = rs.getDate("Lendtime");
                    Date backTime = rs.getDate("Backtime");
                    tableModel.addRow(new Object[]{
                            uno, uname, bno, bname, lendTime, backTime != null ? backTime : "未归还"
                    });
                }
            }
        } catch (SQLException e) {
            throw new SQLException("数据加载失败: " + e.getMessage(), e);
        }
    }
}
